/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.cheetah.sisal.data;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.cheetah.sisal.GetScores;
import org.cheetah.sisal.beans.Avvenimento;
import org.cheetah.sisal.beans.Palinsesto;
import org.cheetah.sisal.sql.Database;
import org.cheetah.sisal.util.AvvenimentoUtil;

/**
 *
 * @author edoardo
 */
public class YouBet {

    public static void main(String[] args) throws Exception {
        Connection con = Database.getConnection();

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(getMaxDate(con));

        Calendar today = Calendar.getInstance();
        today.setTime(new Date());
        List<Date> dates = new ArrayList<Date>();

        while (calendar.before(today)) {
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            PreparedStatement pstmt = con.prepareStatement(Database.getSql("database.count.incontro"));
            pstmt.setDate(1, new java.sql.Date(calendar.getTime().getTime()));
            ResultSet rs = pstmt.executeQuery();
            rs.next();
            if (rs.getInt(1) == 0) {
                dates.add(calendar.getTime());
            }
            rs.close();
            pstmt.close();
        }
        String sql = Database.getSql("database.insert.incontro");
        PreparedStatement pstmt = Database.getPreparedStatement(con, sql);
        con.setAutoCommit(false);
        Map<String, String> presentiSuDB = new HashMap<String, String>();
        List<String> errori = new ArrayList<String>();
        try {
            int row = 0;
            int maxNumberRowsToCommit = 200;

            first:
            for (Date date : dates) {

                Map<String, Palinsesto> palinsesti = GetScores.getRisultati(dateToString(date), true);
                for (Iterator<String> it = palinsesti.keySet().iterator(); it.hasNext();) {
                    String key = it.next();
                    Palinsesto palinsesto = palinsesti.get(key);
                    if (palinsesto != null) {
                        System.out.println(palinsesto);
                        for (Avvenimento avvenimento : palinsesto.getAvvenimentos()) {
                            String _key_ = new StringBuilder(palinsesto.getNumero()).append("|").append(avvenimento.getNumero()).toString();
                            if (!presentiSuDB.containsKey(_key_)) {
                                pstmt.setString(1, palinsesto.getNumero());
                                pstmt.setString(2, avvenimento.getNumero());
                                pstmt.setString(3, avvenimento.getDescrizione());
                                pstmt.setDate(4, new java.sql.Date(date.getTime()));
                                pstmt.setTime(5, null);
                                int gHome = AvvenimentoUtil.golHome(avvenimento.getRisultatoSecondoTempo(), "-");
                                int gAway = AvvenimentoUtil.golAway(avvenimento.getRisultatoSecondoTempo(), "-");
                                pstmt.setString(6, AvvenimentoUtil.getSegnoFinale(gHome, gAway));
                                pstmt.setInt(7, gHome);
                                pstmt.setInt(8, gAway);
                                pstmt.setString(9, avvenimento.getNomeCompetizione());
                                pstmt.addBatch();
                                row++;
//                            if (row == maxNumberRowsToCommit) {
                                try {
                                    pstmt.executeBatch();

                                    pstmt.clearBatch();
                                    pstmt.clearParameters();
                                    row = 0;
//                            }
                                    presentiSuDB.put(_key_, "");
                                } catch (Exception error) {
                                    errori.add(error.getMessage() + "\n\t" + avvenimento);
                                    pstmt.clearBatch();
                                    pstmt.clearParameters();
                                }
                            }
                        }
                    }
                }
                con.commit();

            }
//            if(row<maxNumberRowsToCommit){
//                pstmt.executeBatch();
//                pstmt.clearBatch();
//                pstmt.clearParameters();
//            }
            con.commit();
            pstmt.close();
            con.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Rollback....");
            if (pstmt != null && !pstmt.isClosed()) {
                pstmt.close();
            }
            if (con != null && !con.isClosed()) {
                con.rollback();
                con.close();
            }

        }
        if (errori.size() > 0) {
            System.out.println(errori);
        }
    }

    private static String dateToString(Date date) {
        SimpleDateFormat sdf = (SimpleDateFormat) SimpleDateFormat.getDateInstance();
        sdf.applyPattern("YY_MM_dd");
        String p = sdf.format(date);
        return p;
    }

    private static Date getMaxDate(Connection con) throws SQLException {
        String sqlMax = Database.getSql("database.maxdate.incontro");
        Date maxDate = null;
        PreparedStatement pstmt = con.prepareStatement(sqlMax);
        ResultSet rs = pstmt.executeQuery();
        if (rs.next()) {
            maxDate = rs.getDate(1);
        }
        rs.close();
        pstmt.close();
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, 22);
        calendar.set(Calendar.MONTH, 4);
        calendar.set(Calendar.YEAR, 2005);

        return maxDate==null?new Date(calendar.getTime().getTime()):maxDate;

    }
}
